//
//  MovieModel.cpp
//  ResidentEvil
//
//  Created by Nguyen Tri Chung on 1/7/15.
//
//

#include "MovieModel.h"

MovieModel::MovieModel() {
    playingTape = NULL;
    playing = false;
    elapsedTime = 0;
    curTextureAnimation = NULL;
    curSubTitle = NULL;
}

MovieModel::~MovieModel() {
    Ref::~Ref();
}

// load all tapes from data
// order by start time
void MovieModel::takeTapes() {   
}

void MovieModel::pickTapes(int tapeId) {
    for (auto& tape : tapes) {
        if (tape.tapeId == tapeId) {
            playingTape = &tape;
            return;
        }
    }
    assert(NULL);
}

void MovieModel::eject() {
    if (playingTape == NULL) {
        assert(NULL);
    }
    
    playingTape = NULL;
    playing = false;
}

void MovieModel::play() {
    if (playingTape == NULL) {
        assert(NULL);
    }
    
    playing = true;
    elapsedTime = 0;
    curTextureAnimation = NULL;
    curSubTitle = NULL;
}

void MovieModel::update(float dt) {
    if (!playing) {
        return;
    }
    
    // playing sequence
    elapsedTime += dt;
    if (!curTextureAnimation) {
        TextureAnimation* currentTextureAnimation = findTextureAnimation(elapsedTime);
        if (currentTextureAnimation) {
            curTextureAnimation = currentTextureAnimation;
        }
    }
    
    if (!curSubTitle) {
        SubTitle* currentSubtitle = findSubTitle(elapsedTime);
        if (currentSubtitle) {
            curSubTitle = currentSubtitle;
        }
    }
    
    // show texture animation
    if (curTextureAnimation) {
        
        // check if curTextureAnimation reach end
        if (curTextureAnimation->end < elapsedTime) {
            curTextureAnimation = NULL;
        }
    }
    
    // show subtitle
    if (curSubTitle) {

        // check if curSubTitle reach end
        if (curSubTitle->end < elapsedTime) {
            curSubTitle = NULL;
        }
    }
}

TextureAnimation* MovieModel::findTextureAnimation(float time) {
    if (playingTape == NULL) {
        assert(NULL);
    }

    int count = playingTape->texAnimations.size();
    for (int i = 0; i < count; i++) {
        TextureAnimation* tAnimation = &playingTape->texAnimations.at(i);
        if (time >= tAnimation->start && time <= tAnimation->end) {
            return tAnimation;
        }
    }
    return NULL;
}

SubTitle* MovieModel::findSubTitle(float time) {
    if (playingTape == NULL) {
        assert(NULL);
    }
    
    int count = playingTape->subTitles.size();
    for (int i = 0; i < count; i++) {
        SubTitle* subTitle = &playingTape->subTitles.at(i);
        if (time >= subTitle->start && time <= subTitle->end) {
            return subTitle;
        }
    }
    return NULL;
}